package easy

func IslandPerimeter(grid [][]int) int {
	dx := []int{0, 1, 0, -1}
	dy := []int{1, 0, -1, 0}
	n := len(grid)
	m := len(grid[0])
	ans := 0
	for i := 0; i < n; i++ {
		for j := 0; j < m; j++ {
			if grid[i][j] == 1 {
				cnt := 0
				for k := 0; k < 4; k++ {
					tx := i + dx[k]
					ty := j + dy[k]
					if tx < 0 || tx >= n || ty < 0 || ty >= m || grid[tx][ty] == 0 {
						cnt++
					}
				}
				ans += cnt
			}
		}
	}
	return ans
}
